﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;
using System.Web;
using System.IO;
using System.Security.Cryptography;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    /// <summary>
    /// 培训计划包含培训内容的管理（增删改查）
    /// </summary>
    public class TrainPlanController : ApiController
    {

        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


        // POST: api/TrainPlan
        /// <summary>
        /// 添加培训计划及培训内容，如果培训计划对应的计划名称已经存在，那么就是更新培训计划
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainPlan/Add")]
        public IHttpActionResult Add(ViewModel.VM_Trainplan_View view)
        {
            //string sResult = "";
            var model = view.vM_Trainplan;
            log.Info(JsonConvert.SerializeObject(model));
            Model.TrainPlan mTrainPlan = new Model.TrainPlan();
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                mTrainPlan.TPName = model.TPName;
                mTrainPlan.TPDescribe = model.TPDescribe;
                mTrainPlan.TPIsRelease = 0;// model.TPIsRelease;
                mTrainPlan.TPReleaseStart = model.TPReleaseStart;
                mTrainPlan.TPReleaseEnd = model.TPReleaseEnd;
                mTrainPlan.TPDesignUserID = LoginUser.UserInfo.UserID;//model.TPDesignUserID;
                mTrainPlan.TPDesignUserName = LoginUser.UserInfo.UserName;  //model.TPDesignUserName;
                mTrainPlan.TPDepID = LoginUser.DepID;// model.TPDepID;
                mTrainPlan.TPAddUserID = LoginUser.UserInfo.UserID;
                mTrainPlan.TPAddUserName = LoginUser.UserInfo.UserName;
                mTrainPlan.TPAddDateTime = DateTime.Now;
                mTrainPlan.CPID = model.CPID;
                mTrainPlan.TPID=new BLL.SysManage().GetMaxId("TrainPlan", "TPID");
                mTrainPlan.IsUse = 1;
                mTrainPlan.IsCheck = 0;
                mTrainPlan.TPDescribeContent = model.TPDescribeContent;
                //mTrainPlan.TPSendDepID = model.TPSendDepID;
                //Model.Dep mDep = new BLL.Dep().GetModel(long.Parse(LoginUser.UserInfo.DeptID.ToString()));
                mTrainPlan.TPDepLevel = LoginUser.DepLevel;
                mTrainPlan.TPPID = model.TPPID;
                mTrainPlan.Remarks = model.Remarks;
                BLL.TrainPlan bllTrainPlan = new BLL.TrainPlan();
                BLL.TrainPlanFiles trainCourseFiles = new BLL.TrainPlanFiles();
                if (!bllTrainPlan.Exists(model.TPName,model.TPReleaseStart,model.TPReleaseEnd))
                {
                    //培训计划不存在，添加新的培训计划
                    //增加主表
                    bllTrainPlan.Add(mTrainPlan);
                    #region 处理课程资料配置
                    var listCourseFileModel = new List<Model.TrainPlanFiles>();
                    var list1 = GetFileList(view.vList1, mTrainPlan.TPID, 0);
                    var list2 = GetFileList(view.vList2, mTrainPlan.TPID, 1);
                    listCourseFileModel.AddRange(list1);
                    listCourseFileModel.AddRange(list2);
                    trainCourseFiles.AddList(listCourseFileModel);
                    #endregion
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Count = 1;
                    resultMsg.Data = mTrainPlan.TPID;
                }
                else
                {

                    //培训计划已经存在,获取培训计划对应的ID，此时是更新培训计划及培训计划的内容 
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "培训计划名称已经存在，请不要重复！";
                    resultMsg.Data = "培训计划名称已经存在，请不要重复！";
                }
            }
            catch (Exception exc)
            {

                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = "培训计划增加异常！" + exc.Message;
                resultMsg.Data = "培训计划增加异常！" + exc.Message;
            }
            return Json(resultMsg);
        }
        private List<Model.TrainPlanFiles> GetFileList(List<VM_Content> list, long TPID, int Mark)
        {
            var listCourseFileModel = new List<Model.TrainPlanFiles>();
            if (list == null)
            {
                return listCourseFileModel;
            }
            int num = 0;
            foreach (var item in list)
            {
                if (string.IsNullOrEmpty(item.CName) && item.files.Count == 0)
                { continue; }
                num++;

                if (item.files.Count > 0)
                {
                    foreach (var file in item.files)
                    {
                        if (file.id < 0)
                        {
                            continue;
                        }
                        Model.TrainPlanFiles trainCourseFilesModel = new Model.TrainPlanFiles();
                        trainCourseFilesModel.TContent = item.CName;
                        trainCourseFilesModel.TPID = TPID;
                        trainCourseFilesModel.TCMark = Mark;
                        trainCourseFilesModel.OrderNum = num;
                        trainCourseFilesModel.TFID = file.id;
                        trainCourseFilesModel.TCDuration = item.TCDuration;
                        listCourseFileModel.Add(trainCourseFilesModel);
                    }
                }
            }
            return listCourseFileModel;
        }

        [HttpPost]
        [Route("api/TrainPlan/AddAndFileUpload")]
        public IHttpActionResult AddAndFileUpload()
        {
            log.Info("开始文件上传，文件数：" + HttpContext.Current.Request.Files.Count.ToString());
            Res res = new Res();
            var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;


            log.Info("开始文件上传:");
            var path = "";
            var fileName = "";
            var svrFilePathPlusName = "/uploads/";
            if (file != null && file.ContentLength > 0)
            {
                fileName = Path.GetFileName(file.FileName);
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/uploads")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/uploads"));
                }
                path = Path.Combine(
                    HttpContext.Current.Server.MapPath("~/uploads"),
                    fileName
                );

                log.Info("开始文件上传:" + fileName);
                file.SaveAs(path);
            }
            log.Info("文件数" + HttpContext.Current.Request.Files.Count.ToString() + "=" + fileName + "-" + path);

            Model.TrainPlan target = new Model.TrainPlan();

            var TPID = HttpContext.Current.Request["TPID"].ToString();
            var TPName = HttpContext.Current.Request["TPName"].ToString();
            var CPID = HttpContext.Current.Request["CPID"].ToString();
            var TPPID = HttpContext.Current.Request["TPPID"].ToString();
            var TPDescribe = HttpContext.Current.Request["TPDescribe"].ToString();
            var TPReleaseStart = HttpContext.Current.Request["TPReleaseStart"].ToString();
            var TPReleaseEnd = HttpContext.Current.Request["TPReleaseEnd"].ToString();
            var Remarks = HttpContext.Current.Request["Remarks"].ToString(); 

            target.TPName = TPName;
            target.TPPID = Int32.Parse( TPPID);
            target.CPID = Int32.Parse( CPID);
            DateTime? myDT = new DateTime();
            if (string.IsNullOrEmpty(TPReleaseStart))
                myDT = null;
            else
                myDT = Convert.ToDateTime(TPReleaseStart);
            target.TPReleaseStart = myDT;


            if (string.IsNullOrEmpty(TPReleaseEnd))
                myDT = null;
            else
                myDT = Convert.ToDateTime(TPReleaseEnd);
            target.TPReleaseEnd = myDT;
            //target.TPID = new BLL.SysManage().GetMaxId("TrainPlan", "TPID");
            target.TPDescribe = TPDescribe;
            target.TPDesignUserID = LoginUser.UserInfo.UserID;
            target.TPDesignUserName = LoginUser.UserInfo.UserName; 
            target.IsUse = 1;
            target.TPIsRelease = 0;
            target.IsCheck = 0;
            target.TPDepID = LoginUser.DepID;
            target.TPDepLevel = LoginUser.DepLevel;
            target.TPAddUserID = LoginUser.UserInfo.UserID;
            target.TPAddUserName = LoginUser.UserInfo.UserName;
            target.TPAddDateTime = DateTime.Now;
            target.Remarks = Remarks;
            target.AnnexName = fileName;
            target.AnnexUrl = svrFilePathPlusName + fileName;

            try
            {
                BLL.TrainPlan btp = new BLL.TrainPlan();

                if (new IPR_StudyMeetingMrgSys.BLL.TrainPlan().UpdateAnnex(TPID,target.AnnexName,target.AnnexUrl) > 0)
                {

                    IPR_StudyMeetingMrgSys.Model.TrainFiles mTF = new Model.TrainFiles();
                    //mTF.TFID = new IPR_StudyMeetingMrgSys.BLL.SysManage().GetMaxId("TrainFiles", "TFID");
                    mTF.TFParentID = 0;
                    mTF.TFName = fileName.Split('.')[0];
                    mTF.FTID = 0;
                    mTF.KKID = 0;
                    mTF.TFPath = path;
                    mTF.TFSize = file.ContentLength;
                    mTF.TFMD5 = MD5Encrypt(mTF.TFName, "ZZIPRYFB");
                    mTF.TFUseCount = 0;
                    mTF.TFIsPhoto = ".jpg|.png|.jpeg|.bmp|.gif".Contains(fileName.Split('.')[1]) ? 1 : 0;
                    mTF.TFIsPass = 1;
                    mTF.TFAddUserID = (int)LoginUser.UserInfo.FID;
                    mTF.TFAddUserName = LoginUser.UserInfo.UserName;
                    mTF.TFAddDateTime = DateTime.Now;
                    mTF.TFServerPath = target.AnnexUrl;
                    mTF.TFIsUse = 1;
                    mTF.TFDownCount = 0;
                    mTF.TFUploadDeptID = (int)LoginUser.UserInfo.DeptID;
                    mTF.DepID = LoginUser.UserInfo.DeptID.ToString();
                    if (TPReleaseEnd != "")
                        mTF.TFEndDateTime = TPReleaseEnd == "" ? Convert.ToDateTime("2099-12-31") : Convert.ToDateTime(TPReleaseEnd);

                    bool blExist = new BLL.TrainFiles().Exists(mTF.TFName);
                    if (blExist)
                    {
                        //如果已经存在，说明上传重复，不处理
                        res.code = (int)StatusCodeEnum.NameExists;
                        res.msg = StatusCodeEnum.NameExists.GetEnumText();
                    }
                    else
                    {
                        log.Info("数据库开始存储！");

                        mTF.TFID = new BLL.SysManage().GetMaxId("TrainFiles", "TFID");
                        new BLL.TrainFiles().Add(mTF);

                        res.msg = "增加成功";
                        res.code = 0;
                    }
                }
                else
                {
                    res.msg = "增加失败";
                }
            
            }
            catch (Exception ex)
            {
                res.code = (int)StatusCodeEnum.Error;
                res.msg = StatusCodeEnum.Error.GetEnumText();
                log.Error(ex);
            }



            return Json(res);
        }

        public string MD5Encrypt(string pToEncrypt, string sKey)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(pToEncrypt);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("X");
            }

            return byte2String;
        }
        /// <summary>
        /// 试卷查询
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainPlan/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                swhere = swhere ?? string.Empty;
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;
                if (!string.IsNullOrWhiteSpace(swhere))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = " 1=1 and IsUse=1 ";
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "TPName")
                        {if((item.Value!="")&&(item.Value!=null))
                            swhere += $" AND TPName like '%{item.Value}%' ";
                        }
                        if (item.Key == "TPReleaseStart")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND TPReleaseStart >= convert(varchar(20),'{item.Value}',120) ";
                        }
                        if (item.Key == "TPReleaseEnd")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND TPReleaseEnd <= convert(varchar(20),'{item.Value}',120) ";
                        }
                        if (item.Key == "IsCheck")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND IsCheck ={item.Value} ";
                        }
                        //if (item.Key == "TPIsRelease")
                        //{
                        //    if ((item.Value != "") && (item.Value != null))
                        //        swhere += $" AND TPIsRelease ={item.Value} ";
                        //}
                       
                        if (item.Key== "self")
                        {
                            string before = " and "+swhere;

                            if ((item.Value != "") && (item.Value != null))
                            {
                                switch (item.Value)
                                {
                                    case "0"://列表页 ,当前部门,上级部门,审核，发布
                                        switch (LoginUser.DepLevel)
                                        {
                                            case 0:
                                                #region 段读取所有计划信息[状态为 已发布,已审核]
                                                swhere += $" AND ( TPDepLevel>" + LoginUser.DepLevel + " and IsCheck='1')";
                                                swhere += $" or ( TPDepLevel=" + LoginUser.DepLevel + " AND TPDepID=" + LoginUser.DepID + " "+before+ " )";
                                                #endregion
                                                break;
                                            default:
                                                //下发给当前部门的计划
                                                swhere += " and TPID in (select A.TPID from TrainPlanSendDept AS A left join  TrainPlanSendStep  AS B ON A.TPSSID=B.SendID where A.TPSDDeptID = '" + LoginUser.DepID+ "' AND B.SendState='1')";
                                                swhere += $" or ( TPDepLevel=" + LoginUser.DepLevel + " AND TPDepID=" + LoginUser.DepID + "  " + before + ")";
                                                break;
                                        }
                                        break;
                                    case "1":
                                        swhere += "  AND (TPReleaseEnd >= convert(varchar(20),'" + DateTime.Now + "',120)  and IsCheck='1') or ( IsCheck='1' and TPDepID='" + LoginUser.DepID+"') and TPID in (select A.TPID from TrainPlanSendDept AS A left join  TrainPlanSendStep  AS B ON A.TPSSID=B.SendID where A.TPSDDeptID = '" + LoginUser.DepID + "' AND B.SendState='1')";
                                        break;
                                    case "2":
                                        swhere += " and TPID in (select A.TPID from TrainPlanSendDept AS A left join  TrainPlanSendStep  AS B ON A.TPSSID=B.SendID where A.TPSDDeptID = '" + LoginUser.DepID + "' AND B.SendState='1')";
                                        swhere += $" or TPDepID=" + LoginUser.DepID + " and IsCheck='1'   ";
                                        break;
                                }
                                
                            }
                        }
                    }
                }

                bool blExist = false;
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainPlan().GetListByPage(swhere, "TPID", startindex, endindex,out rowCount);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowCount;
                            blExist = true;
                        }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText()+exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }
        [HttpGet]
        [Route("api/TrainPlan/GetContent")]
        public IHttpActionResult GetContent(string TPID)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                Contents contents = new Contents();
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainPlanFiles().GetListView(" a.TPID='" + TPID + "' ORDER by a.TCMark asc ");
                Contents result = new Contents();
                if (dsSearch != null)
                {
                    if (dsSearch.Tables.Count > 0)
                    {
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            DataRow[] dataRowChild = dsSearch.Tables[0].Select(string.Format(@"TCMark={0}", 0));
                            DataRow[] dataRowChild2 = dsSearch.Tables[0].Select(string.Format(@"TCMark={0}", 1));
                            #region 1
                            result.vList1 = new List<VM_Content>();
                            GetResultContentList(dataRowChild, result, 0);
                            GetResultContentList(dataRowChild2, result, 1);
                            #endregion
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = result;
                        }
                    }
                }
                //if (mTP != null && mTP.TPID != 0)
                //{
                //    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                //    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                //    resultMsg.Data = mTP;
                //}
                //else
                //{
                //    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                //    resultMsg.Info = "数据不存在！";
                //}
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "内部请求出错 " + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 培训计划编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainPlan/Edit")]
        public IHttpActionResult Edit(VM_Trainplan_View view)
        {
            var model = view.vM_Trainplan;
            Model.TrainPlan mTrainPlan = new Model.TrainPlan();
            log.Info(JsonConvert.SerializeObject(model));
            model.TPAddUserID = LoginUser.UserInfo.UserID;
            model.TPAddUserName = LoginUser.UserInfo.UserName;
            model.TPAddDateTime = DateTime.Now;
            ResultMsg resultMsg = new ResultMsg();
            mTrainPlan.TPName = model.TPName;
            mTrainPlan.TPDescribe = model.TPDescribe;
            mTrainPlan.TPIsRelease = 0;// model.TPIsRelease;
            mTrainPlan.TPReleaseStart = model.TPReleaseStart;
            mTrainPlan.TPReleaseEnd = model.TPReleaseEnd;
            mTrainPlan.TPDesignUserID = LoginUser.UserInfo.UserID;//model.TPDesignUserID;
            mTrainPlan.TPDesignUserName = LoginUser.UserInfo.UserName;  //model.TPDesignUserName;
            mTrainPlan.TPDepID = LoginUser.DepID;// model.TPDepID;
            mTrainPlan.TPAddUserID = LoginUser.UserInfo.UserID;
            mTrainPlan.TPAddUserName = LoginUser.UserInfo.UserName;
            mTrainPlan.TPAddDateTime = DateTime.Now;
            mTrainPlan.CPID = model.CPID;
            mTrainPlan.TPID = model.TPID;
            mTrainPlan.IsUse = 1;
            mTrainPlan.IsCheck = 0;
            mTrainPlan.TPDescribeContent = model.TPDescribeContent;
            //mTrainPlan.TPSendDepID = model.TPSendDepID;
            //Model.Dep mDep = new BLL.Dep().GetModel(long.Parse(LoginUser.UserInfo.DeptID.ToString()));
            mTrainPlan.TPDepLevel = LoginUser.DepLevel;
            mTrainPlan.TPPID = model.TPPID;
            mTrainPlan.Remarks = model.Remarks;
            try
            {
                string errorMsg = string.Empty;
                BLL.TrainPlanFiles trainPlanFiles = new BLL.TrainPlanFiles();
                if (new IPR_StudyMeetingMrgSys.BLL.TrainPlan().Update(mTrainPlan, out errorMsg))
                {
                    if (string.IsNullOrEmpty(errorMsg))
                    {
                        var listCourseFileModel = new List<Model.TrainPlanFiles>();
                        var list1 = GetFileList(view.vList1, view.vM_Trainplan.TPID,0);
                        var list2 = GetFileList(view.vList2,view.vM_Trainplan.TPID,1);
                        listCourseFileModel.AddRange(list1);
                        listCourseFileModel.AddRange(list2);
                        trainPlanFiles.AddList(listCourseFileModel, model.TPID);
                    }
                    resultMsg.Info = "编辑成功";
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Count = 1;
                    resultMsg.Data = model.TPID;
                }
                else
                {
                    resultMsg.Info = errorMsg;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
            }
            return Json(resultMsg);
        }
        private void GetResultContentList(DataRow[] dataRowChild, Contents result, int mark)
        {
            int cnum = -1;
            VM_Content vM_ContentDetail = new VM_Content();
            int i = 0; int x = 0;
            foreach (var item in dataRowChild)
            {
                int num = item["OrderNum"] == null ? 0 : Convert.ToInt32(item["OrderNum"].ToString());
                if (cnum != num)
                {
                    if (cnum != -1)
                    {
                        x++;
                        switch (mark)
                        {
                            case 0:
                                result.vList1.Add(vM_ContentDetail);
                                break;
                            case 1: result.vList2.Add(vM_ContentDetail); break;
                        }
                    }
                    vM_ContentDetail = new VM_Content();
                    vM_ContentDetail.files = new List<VM_ContentFile>();
                    cnum = num;
                }
                vM_ContentDetail.idx = x.ToString();
                vM_ContentDetail.CName = item["TContent"] == null ? "" : item["TContent"].ToString();
                vM_ContentDetail.TCDuration = item["TCDuration"] == null ? 0 : Convert.ToInt32(item["TCDuration"].ToString() == "" ? "0" : item["TCDuration"].ToString());
                long tfid = item["TFID"] == null ? 0 : Convert.ToInt64(item["TFID"]);
                string tfname = item["TFName"] == null ? "" : item["TFName"].ToString();
                vM_ContentDetail.files.Add(new VM_ContentFile() { id = tfid, name = tfname });
                if (i == dataRowChild.Length - 1)
                {
                    switch (mark)
                    {
                        case 0:
                            result.vList1.Add(vM_ContentDetail);
                            break;
                        case 1: result.vList2.Add(vM_ContentDetail); break;
                    }
                }
                i++;
            }
        }
        /// <summary>
        /// 培训计划删除(根据人员工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainPlan/Del")]
        public IHttpActionResult Del(Model.TrainPlan model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                    if (new IPR_StudyMeetingMrgSys.BLL.TrainPlan().Delete(model.AutoID))
                    {
                        resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                        resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                        resultMsg.Data = "培训计划删除成功！";
                    }
                    else
                    {
                        resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                        resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                        resultMsg.Data = "培训计划删除失败！";
                    }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "培训计划删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 培训计划信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainPlan/DelList")]
        public IHttpActionResult DelList(string delidlist)
        {
            log.Info(JsonConvert.SerializeObject(delidlist));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                var rows = new IPR_StudyMeetingMrgSys.BLL.TrainPlan().DeleteList(delidlist);
                if (rows>0)
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "培训计划删除成功！"+ rows + "条符合删除条件,已删除";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Data = "删除失败，删除0行(仅删除未审核未发布的计划)"; 
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 培训计划发布
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainPlan/Release")]
        public IHttpActionResult ReleaseList(string TCOIDlist)
        {
            log.Info(JsonConvert.SerializeObject(TCOIDlist));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainPlan().Release(TCOIDlist))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "培训计划删除成功！";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "删除成功，删除0行";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 培训计划信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainPlan/GetSingle")]
        public IHttpActionResult GetSingle(string TPID)
        {
            log.Info(JsonConvert.SerializeObject(TPID));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                Model.TrainPlan mTP = new IPR_StudyMeetingMrgSys.BLL.TrainPlan().GetModel( Int32.Parse( TPID));
                if (mTP!=null&&mTP.TPID!=0)
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = mTP;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "已选择的计划不存在(或已被删除)！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "内部请求出错 " + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 培训计划信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainPlan/Sel")]
        public IHttpActionResult Sel()
        {

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                bool blexist = false;
                DataSet ds= new IPR_StudyMeetingMrgSys.BLL.TrainPlan().GetList(" IsUse=1 and IsCheck=1 and TPDepLevel!=0 ");
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if(ds.Tables[0].Rows.Count>0)
                        {
                            blexist = true;
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText(); 
                            resultMsg.Data = ds.Tables[0];
                        }
                if(!blexist)
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "已选择的计划不存在(或已被删除)！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "内部请求出错 " + exc.Message;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 更新计划的状态，包含(审核、取消审核、发布、取消发布、使用、未使用)
        /// value 为0时表示取消审核/发布/使用中，为1时表未取消审核/取消发布/未使用
        /// </summary>
        /// <param name="mark">标记码，审核：C / 发布：R / 使用：U</param>
        /// <param name="value">1/0</param>
        /// <param name="wherevalue">条件，使用主键字段值 </param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainPlan/UpdatePlanStatus")]
        public IHttpActionResult UpdatePlanStatus(string mark, string value, string wherevalue)
        {
            log.Info(JsonConvert.SerializeObject(mark + "=" + value));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                string tablename = "TrainPlan";
                string fieldname = "";
                string fieldvalue = "";
                string wherefield = "TPID";
                if (mark == "C")
                {
                    fieldname = "IsCheck";
                }
                if (mark == "R")
                {
                    fieldname = "TPIsRelease";
                }
                if (mark == "U")
                {
                    fieldname = "IsUse";
                }
                fieldvalue = value;
                string ErrorMsg = string.Empty;
                new BLL.SysManage().ExecuteUpdate(tablename, fieldname, fieldvalue, wherefield, wherevalue, out ErrorMsg);
                if (string.IsNullOrEmpty(ErrorMsg))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "更新成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = ErrorMsg;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        // GET: api/TrainPlan
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/TrainPlan/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/TrainPlan
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/TrainPlan/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/TrainPlan/5
        public void Delete(int id)
        {
        }
    }
}
